package com.mmall.service.impl;

import com.mmall.commons.Const;
import com.mmall.commons.ServerResponse;
import com.mmall.commons.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 用户Service 实现类
 * @author wgt
 * @date 2018/6/23
 * @project mmall-server
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        if (!user.getPassword().equals(MD5Util.MD5EncodeUtf8(password))){
            return ServerResponse.createByErrorMessage("密码不正确");
        }

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse register(User user) {
        int resultCount = userMapper.checkUsername(user.getUsername());
        if (resultCount > 0){
            return ServerResponse.createByErrorMessage("用户名已经存在");
        }

        resultCount = userMapper.checkEmail(user.getEmail());
        if (resultCount > 0){
            return ServerResponse.createByErrorMessage("email已经存在");
        }

        String password = user.getPassword();
        user.setPassword(MD5Util.MD5EncodeUtf8(password));
        user.setRole(Const.Role.ROLE_CUSTOMER);

        resultCount = userMapper.insert(user);
        if (resultCount > 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse checkValid(String str, String type) {
        
        if (Const.EMAIL.equals(type)){
            int resultCount = userMapper.checkEmail(str);
            if (resultCount > 0){
                return ServerResponse.createByErrorMessage("email已经存在");
            }
            return ServerResponse.createBySuccessMessage("校验成功");
        }

        if (Const.USERNAME.equals(type)){
            int resultCount = userMapper.checkEmail(str);
            if (resultCount > 0){
                return ServerResponse.createByErrorMessage("email已经存在");
            }
            return ServerResponse.createBySuccessMessage("校验成功");
        }

        return ServerResponse.createByErrorMessage("参数错误");
    }

    @Override
    public ServerResponse<String> selectQuestion(String username) {
        ServerResponse serverResponse = this.checkValid(username, Const.USERNAME);

        if (serverResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }


        String question = userMapper.selectQuestion(username);

        //TODO 验证用户的问题是否存在， 不过问题是 "假设没有问题的话" 该用户是否已经无法找回 ?
        return ServerResponse.createBySuccess(question);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int resultCount = userMapper.checkAnswer(username, question, answer);

        if (resultCount > 0){
            String token = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, token);
            return ServerResponse.createBySuccess(token);
        }

        return ServerResponse.createByErrorMessage("答案错误");
    }

    @Override
    public ServerResponse forgetResetPassword(String username, String password, String token) {
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("缺少参数token");
        }
        String cacheToken = TokenCache.getValue(TokenCache.TOKEN_PREFIX + username);
        if(StringUtils.isNotBlank(cacheToken) && cacheToken.equals(token)){
            ServerResponse serverResponse = this.checkValid(username, Const.USERNAME);
            if (serverResponse.isSuccess()){
                return ServerResponse.createByErrorMessage("用户不存在");
            }

            int updateCount = userMapper.updatePassword(username, MD5Util.MD5EncodeUtf8(password));

            if (updateCount > 0){
                return ServerResponse.createBySuccessMessage("重置密码成功");
            }

            return ServerResponse.createByErrorMessage("重置密码失败");
        }

        return ServerResponse.createByErrorMessage("token错误或已经失效");
    }

    @Override
    public ServerResponse resetPassword(String username, String oldPassword, String newPassword) {
        User user = userMapper.selectByUsername(username);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        if (StringUtils.equals(user.getPassword(), MD5Util.MD5EncodeUtf8(oldPassword))){
            int updateCount = userMapper.updatePassword(username, MD5Util.MD5EncodeUtf8(newPassword));
            if (updateCount > 0){
                return ServerResponse.createBySuccessMessage("重置密码成功");
            }
            return ServerResponse.createByErrorMessage("重置密码失败");
        }

        return ServerResponse.createByErrorMessage("旧密码不正确");
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        if (StringUtils.isNotBlank(user.getEmail())){
            int existId = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
            if (existId > 0){
                return ServerResponse.createByErrorMessage("email 已经存在");
            }
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0){
            return ServerResponse.createBySuccess("个人信息更新成功!", updateUser);
        }
        return ServerResponse.createByErrorMessage("个人信息更新失败");
    }


    @Override
    public ServerResponse getUserInformation(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }


}
